import { Injectable, Inject, HttpException } from '@nestjs/common';
import { Model ,Types} from 'mongoose';
import { AuthService } from 'src/admin/auth/admin.service';
import { AdminUser } from 'src/db/schemas/admin/admin-user.schema';
import { User } from 'src/db/schemas/user/user.schema';
import { AddUser, AdminLoginDto, EditUser , QueryAdminUserDto, UserId } from './user.dto'
import { IRequest } from 'src/interface/common';
/**用户模块服务 */
@Injectable()
export class UserService {
	constructor(
		@Inject('ADMIN_USER_MODEL')
		private readonly UserModel: Model<AdminUser>,
		private readonly authService: AuthService,
	) { }

	async init():Promise<string>{
		let superAdmin=await this.UserModel.findOne({userType:'0'});
		if(superAdmin){
			return 'ok'
		}else{
			let newAdmin=new this.UserModel({
				userName:"xiaobaozi",
				passWord:"123456",
				userType:"0"
			})
			await newAdmin.save()
			return 'ok'
		}
	}

	async login(loginDto: AdminLoginDto){
		let user=await this.UserModel.findOne({userName:loginDto.userName,passWord:loginDto.passWord})
		if(user){
			let {token} =await this.authService.createToken(user)
			return {
				user,token
			}
		}else{
			throw new HttpException({
				code:1,
				message:'账号不存在或密码错误'
			},200)
		}
	}

	async getInfo(req:IRequest){
		let user=await this.UserModel.findById(req.user.userId)
		return user
	}

	async findUser(query:QueryAdminUserDto,req:IRequest){
		let filter:{[x:string]:any}={
			userType:"1"
		}
		if(query.nickName){
			filter.nickName={ $regex: new RegExp(query.nickName, 'i') }
		}
		let total=await this.UserModel.countDocuments(filter)
		let list=await this.UserModel.find(filter).sort({_id:-1}).skip((query.page-1)*query.size).limit(query.size)
		return {
			total,
			list,
			page:query.page,
			size:query.size
		};
	}

	async addUser(Dto: AddUser){
		var user=new this.UserModel(Dto)
		await user.save()
		return "ok"
	}

	async updateUser(body){
		let doc=await this.UserModel.findById(body.id)
		for (const key in body) {
			if (Object.prototype.hasOwnProperty.call(body, key)) {
				const value = body[key];
				if(key!="id"&&Object.prototype.hasOwnProperty.call(doc.toObject(), key)){
					doc[key]=value
				}
			}
		}
		await doc.save()
		return "ok"
	}

	async deleteUser(id:string){
		return this.UserModel.deleteOne({_id:id})
	}
}
